package com.googlecode.recycled.lang.jse.api.io;

import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import com.googlecode.recycled.lang.assertions.Assert;
import org.apache.commons.lang.UnhandledException;

import java.io.*;
import java.nio.charset.Charset;

/**
 * Extensions to Guava CharStreams class.
 *
 * @author Henryk Konsek
 */
public class CharStreamsExt {

    /**
     * Default UTF-8 charset to be used by Recycled of instead platform-dependent Charset.defaultCharset().
     */
    public static final Charset DEFAULT_CHARSET = Charsets.UTF_8;

    /**
     * Name (String) of the CharStreamsExt#DEFAULT_CHARSET.
     */
    public static final String DEFAULT_CHARSET_NAME = DEFAULT_CHARSET.name();

    /**
     * Private constructor - class is intended to being used only as an utility.
     */
    private CharStreamsExt() {
    }

    public static String toString(InputStream inputStream) {
        Assert.notNull(inputStream);

        try {
            return CharStreams.toString(InputSuppliers.asInputSupplier(new InputStreamReader(inputStream, DEFAULT_CHARSET)));
        } catch (IOException e) {
            throw new UnhandledException(e);
        }
    }

    public static String toString(byte[] bytes) {
        Assert.notEmpty(bytes);

        return new String(bytes, DEFAULT_CHARSET);
    }

    public static Reader newReader(InputStream inputStream, Charset charset) {
        Assert.notNull(inputStream);
        Assert.notNull(charset);

        return new BufferedReader(new InputStreamReader(inputStream, charset));
    }

    public static Reader newReader(InputStream inputStream) {
        return new BufferedReader(new InputStreamReader(Assert.notNull(inputStream), DEFAULT_CHARSET));
    }

    public static ByteArrayInputStream asByteInputStream(String string) {
        return asByteInputStream(string, DEFAULT_CHARSET);
    }

    public static ByteArrayInputStream asByteInputStream(String string, Charset charset) {
        Assert.notNull(string);
        Assert.notNull(charset);
        return new ByteArrayInputStream(string.getBytes(charset));
    }

}
